`timescale 1ns/1ns
module S_E_process
#(
	parameter	[10:0]	IMG_HDISP = 11'd1080,	
	parameter	[10:0]	IMG_VDISP = 11'd720
)
(
	
	input				clk,  				
	input				rst_n,				

	
	input				per_frame_v,	
	input				per_frame_h,		
	input		[7:0]	per_img_Gray,		
	
	
	output				post_frame_v,	
	output				post_frame_h,	
	output				post_img_Bit,		
	
	
	input		[7:0]	Sobel_Threshold		
);


wire				matrix_frame_v;	
wire				matrix_frame_h;	
wire		[7:0]	matrix_p11, matrix_p12, matrix_p13;	
wire		[7:0]	matrix_p21, matrix_p22, matrix_p23;
wire		[7:0]	matrix_p31, matrix_p32, matrix_p33;
Matrix_Generate_3X3_8Bit	
#(
	.IMG_HDISP	(IMG_HDISP),	//1080*720
	.IMG_VDISP	(IMG_VDISP)
)
u_Matrix_Generate_3X3_8Bit
(
	
	.clk					(clk),  				
	.rst_n					(rst_n),				

	
	.per_frame_v		(per_frame_v),		
	.per_frame_h			(per_frame_h),		
	.per_img_Gray			(per_img_Gray),			

	
	.matrix_frame_v		(matrix_frame_v),	
	.matrix_frame_h		(matrix_frame_h),	
	.matrix_p11(matrix_p11),	.matrix_p12(matrix_p12), 	.matrix_p13(matrix_p13),	
	.matrix_p21(matrix_p21), 	.matrix_p22(matrix_p22), 	.matrix_p23(matrix_p23),
	.matrix_p31(matrix_p31), 	.matrix_p32(matrix_p32), 	.matrix_p33(matrix_p33)
);


//步骤一
reg	[9:0]	Gx_temp1;	
reg	[9:0]	Gx_temp2;	
reg	[9:0]	Gx_data;	
always@(posedge clk or negedge rst_n)
begin
	if(!rst_n)
		begin
		Gx_temp1 <= 0;
		Gx_temp2 <= 0;
		Gx_data <= 0;
		end
	else
		begin
		Gx_temp1 <= matrix_p13 + (matrix_p23 << 1) + matrix_p33;	
		Gx_temp2 <= matrix_p11 + (matrix_p21 << 1) + matrix_p31;	
		Gx_data <= (Gx_temp1 >= Gx_temp2) ? Gx_temp1 - Gx_temp2 : Gx_temp2 - Gx_temp1;
		end
end

//步骤二
reg	[9:0]	Gy_temp1;	
reg	[9:0]	Gy_temp2;	
reg	[9:0]	Gy_data;	
always@(posedge clk or n
begin
	if(!rst_n)
		begin
		Gy_temp1 <= 0;
		Gy_temp2 <= 0;
		Gy_data <= 0;
		end
	else
		begin
		Gy_temp1 <= matrix_p11 + (matrix_p12 << 1) + matrix_p13;	//正数
		Gy_temp2 <= matrix_p31 + (matrix_p32 << 1) + matrix_p33;	//负数
		Gy_data <= (Gy_temp1 >= Gy_temp2) ? Gy_temp1 - Gy_temp2 : Gy_temp2 - Gy_temp1;
		end
end


//步骤三
reg	[20:0]	Gxy_square;
always@(posedge clk or negedge rst_n)
begin
	if(!rst_n)
		Gxy_square <= 0;
	else
		Gxy_square <= Gx_data * Gx_data + Gy_data * Gy_data;
end

//步骤四
wire	[10:0]	Dim;
SQRT	u_SQRT
(
	.radical	(Gxy_square),
	.q			(Dim),
	.remainder	()
);

//步骤五
reg	post_img_Bit_r;
always@(posedge clk or negedge rst_n)
begin
	if(!rst_n)
		post_img_Bit_r <= 1'b0;	//默认
	else if(Dim >= Sobel_Threshold)
		post_img_Bit_r <= 1'b1;	//边缘标志
	else
		post_img_Bit_r <= 1'b0;	//非边缘
end


reg	[4:0]	per_frame_v_r;
reg	[4:0]	per_frame_h_r;	
always@(posedge clk or negedge rst_n)
begin
	if(!rst_n)
		begin
		per_frame_v_r <= 0;
		per_frame_h_r <= 0;
		end
	else
		begin
		per_frame_v_r 	<= 	{per_frame_v_r[3:0], 	matrix_frame_v};
		per_frame_h_r 	<= 	{per_frame_h_r[3:0], 	matrix_frame_h};
		end
end
assign	post_frame_v 	= 	per_frame_v_r[4];
assign	post_frame_h 	= 	per_frame_h_r[4];
assign	post_img_Bit		=	post_frame_h ? post_img_Bit_r : 1'b0;

endmodule
